import React from "react";
import { messages } from "share/common";
import { Form, Input, Select, Row } from "antd";
import AddBankAccount from "./add-bank-account";
import corporatePaymentReportService from "../../corporate-payment-report.service";
import WrapFormItem from "components/wrap-form-item";
const Option = Select.Option;
const FormItem = Form.Item;

class PayeeInfo extends React.Component {
  state = {
    accountNumber: "",
    accountName: "",
  };

  componentDidMount() {
    this.setState({
      accountNumber: this.props.accountNumber,
      accountName: this.props.accountName,
    });
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      accountNumber: nextProps.accountNumber,
      accountName: nextProps.accountName,
    });
  }

  onChangePayeeInfo = (willSetValue) => {
    this.props.form.setFieldsValue({ ...willSetValue });
    this.props.onChangePayeeInfo && this.props.onChangePayeeInfo(willSetValue);
  };

  render() {
    const { accountNumber, accountName } = this.state;
    const { isAuditEditable, hasSupplierSetting, expenseInfo, expenseTypeId } = this.props;
    const { getFieldDecorator } = this.props.form;
    return (
      <div>
        <FormItem label={messages("finance-9.key10") /*收款方账号*/} required>
          {getFieldDecorator("accountNumber", {
            initialValue: accountNumber,
            rules: [
              {
                required: true,
                message: messages("common.please.select"),
              },
            ],
          })(
            <WrapFormItem parser={(val) => val || ""}>
              {(onChange, value) => (
                <PayeeNumber
                  accountNumber={value}
                  onChangePayeeNumber={(willSetValue) => {
                    onChange(willSetValue);
                    this.onChangePayeeInfo(willSetValue);
                  }}
                  isAuditEditable={isAuditEditable}
                  hasSupplierSetting={hasSupplierSetting}
                  expenseInfo={expenseInfo}
                  expenseTypeId={expenseTypeId}
                />
              )}
            </WrapFormItem>
          )}
        </FormItem>
        <FormItem label={messages("finance-9.key11") /*收款方户名*/} required>
          {getFieldDecorator("accountName", {
            initialValue: accountName,
            rules: [
              {
                required: true,
                message: messages("common.please.input"),
              },
            ],
          })(<Input disabled={true} placeholder={messages("common.please.input")} />)}
        </FormItem>
      </div>
    );
  }
}

class PayeeNumber extends React.Component {
  state = {
    bankListOption: [],
    accountNumber: "",
  };

  componentDidMount() {
    this.setState({ accountNumber: this.props.accountNumber });
    this.getBankList(this.props.expenseTypeId);
  }

  componentWillReceiveProps(nextProps) {
    this.setState({ accountNumber: nextProps.accountNumber });
    if (nextProps.expenseTypeId !== this.props.expenseTypeId) this.getBankList(nextProps.expenseTypeId);
  }

  getBankList = async (expenseTypeId) => {
    const { expenseInfo } = this.props;
    const res = await corporatePaymentReportService.getCostCenterItems(expenseInfo.expenseReportOID);
    let params = {
      vendorInfoId: expenseInfo.corpSupplierId,
      expenseTypeId: expenseTypeId,
      status: 1001,
      costCenterItemIds: res.data,
    };
    corporatePaymentReportService.getBanks(params).then((res) => {
      let bankInfo = res.data || {};
      this.setState(
        {
          bankListOption: bankInfo.venBankAccountBeans || [],
          vendorInfo: {
            id: bankInfo.id,
            venNickname: bankInfo.venNickname,
            venderCode: bankInfo.venderCode,
            source: bankInfo.source,
            venderTypeId: bankInfo.venderTypeId,
            venderTypeName: bankInfo.venderTypeName,
          },
        },
        this.initAccountNumber
      );
    });
  };

  initAccountNumber = () => {
    const { accountNumber, bankListOption } = this.state;
    if (!accountNumber) {
      if (bankListOption.length === 1) this.onChangePayeeNumber(bankListOption[0].bankAccount);
      else if (bankListOption.filter((i) => !!i.primaryFlag).length)
        this.onChangePayeeNumber(bankListOption.filter((i) => !!i.primaryFlag)[0].bankAccount);
      else {
        bankListOption[0] && this.onChangePayeeNumber(bankListOption[0].bankAccount);
      }
    }
  };

  onChangePayeeNumber = (value) => {
    const { bankListOption } = this.state;
    let selectedAccount = bankListOption.filter((i) => i.bankAccount === value)[0];
    this.props.onChangePayeeNumber({
      accountNumber: value,
      accountName: selectedAccount.venBankNumberName,
    });
  };

  refreshBankOptions = (bankListOption, resetFields) => {
    this.setState({ bankListOption: bankListOption, ...resetFields });
    this.props.onChangePayeeNumber(resetFields);
  };

  formatBankNumber = (value) => {
    if (typeof value !== "string") return value;
    return value.replace(/(^\d{4})(\d+)(\d{4}$)/, (target, $1, $2, $3) => {
      return $1 + $2.replace(/./g, "*") + $3;
    });
  };

  render() {
    const { bankListOption, vendorInfo, accountNumber } = this.state;
    const { isAuditEditable, hasSupplierSetting, expenseInfo } = this.props;
    return (
      <Row>
        <Select
          value={accountNumber}
          className="normal-width"
          getPopupContainer={(triggerNode) => triggerNode.parentNode}
          onChange={this.onChangePayeeNumber}
          placeholder={messages("common.please.select")}
        >
          {bankListOption.map((item) => (
            <Option
              key={item.bankAccount}
              style={{ whiteSpace: "normal" }}
              title={`${item.bankAccount} ${item.bankName}`}
            >
              {this.formatBankNumber(item.bankAccount)} {item.bankName}
            </Option>
          ))}
        </Select>
        <AddBankAccount
          vendorInfo={vendorInfo}
          expenseInfo={expenseInfo}
          isAuditEditable={isAuditEditable}
          hasSupplierSetting={hasSupplierSetting}
          bankListOption={bankListOption}
          refreshBankOptions={this.refreshBankOptions}
        />
      </Row>
    );
  }
}

PayeeInfo.PayeeNumber = PayeeNumber;

export default PayeeInfo;
